package com.ljfiction.book.activitys;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.BiaoqianmoreBean;
import com.ljfiction.book.Dialog.LoadingDIalog;
import com.ljfiction.book.Dialog.LoadviewDialog;
import com.ljfiction.book.Dialog.NoBackgLodDialog;
import com.ljfiction.book.MyView.DividerItemDecoration;
import com.ljfiction.book.MyView.SuperButton;
import com.ljfiction.book.R;
import com.ljfiction.book.adapter.MoreBiaoqianAdapter;
import com.ljfiction.book.adapter.TextViewAdapter;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.tools.ScreenUtils;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

public class ClassfimuchActivity extends BaseActivity {

    @BindView(R.id.back_classfymuch)
    ImageView backClassfymuch;
    @BindView(R.id.classfy_title)
    TextView classfyTitle;
    @BindView(R.id.seniority)
    LinearLayout seniority;
    @BindView(R.id.screen)
    LinearLayout screen;
    @BindView(R.id.recycle_muchclass)
    RecyclerView recycleMuchclass;
    @BindView(R.id.rankimage)
    ImageView rankimage;
    @BindView(R.id.shaixuanimage)
    ImageView shaixuanimage;
    @BindView(R.id.refresh_classify)
    SmartRefreshLayout refreshClassify;
    @BindView(R.id.nodatas_classfy)
    LinearLayout nodatasClassfy;
    @BindView(R.id.classfymuchtop)
    RelativeLayout classfymuchtop;

    private PopupWindow popupWindow, popuWindowRank;
    private RankViewHolder viewHolder;
    private LoadviewDialog noBackgLodDialog;
    private List<String> listNum = new ArrayList<>();
    private List<String> listZhuangtai = new ArrayList<>();
    private List<String> listTime = new ArrayList<>();
    private List<String> listRank = new ArrayList<>();
    private List<BiaoqianmoreBean.DataBean.ListBean> booklist = new ArrayList<>();
    private int numPosition = 0;
    private int zhuangTaiPosition = 0;
    private int timePosition = 0;
    private int rankPosition = 2;

    private String lableid;

    public int getNumPosition() {
        return numPosition;
    }

    public int getZhuangTaiPosition() {
        return zhuangTaiPosition;
    }

    public int getTimePosition() {
        return timePosition;
    }

    public int getRankPosition() {
        return rankPosition;
    }

    private int page = 1;
    private BiaoqianmoreBean booklistBean;
    private MoreBiaoqianAdapter adapter;
    private TextViewAdapter numAdapter, zhuangtaiAdapter, timeAdapter, rankAdapter;
    private RecyclerView ranrecycle;
    private SuperButton okrank;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classfimuch);
        ButterKnife.bind(this);
        lableid = getIntent().getStringExtra("id");
        classfyTitle.setText(getIntent().getStringExtra("name"));
        intView();
        intData();
        intStringdata();
    }

    private void intView() {
        adapter = new MoreBiaoqianAdapter(R.layout.morexiaobian_item, booklist);
        recycleMuchclass.setAdapter(adapter);
        recycleMuchclass.setLayoutManager(new LinearLayoutManager(this));
        recycleMuchclass.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                intent = new Intent(ClassfimuchActivity.this, BookDetailsActivity.class);
                intent.putExtra("bookId", String.valueOf(booklist.get(position).getBookId()));
                startActivity(intent);
            }
        });
        refreshClassify.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                if (booklistBean.getData().isIsLastPage()) {
                    refreshClassify.finishLoadMore();
                    refreshClassify.setEnableLoadMore(false);
                } else {
                    page++;
                    intData();
                }

            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                booklist.clear();
                refreshClassify.setEnableLoadMore(true);
                intData();
            }
        });
    }

    private void intStringdata() {
        listNum.add("不限字数");
        listNum.add("30万以下");
        listNum.add("30-50万");
        listNum.add("50-100万");
        listNum.add("100-200万");
        listNum.add("200万以上");
        listZhuangtai.add("不限状态");
        listZhuangtai.add("连载中");
        listZhuangtai.add("已完结");
        listZhuangtai.add("已出版");
        listTime.add("不限时间");
        listTime.add("本日");
        listTime.add("三日");
        listTime.add("七日");
        listTime.add("半月内");
        listTime.add("一月内");
        listRank.add("金椒排序");
        listRank.add("推荐排序");
        listRank.add("点击排序");
        listRank.add("新书排序");
        listRank.add("销量排序");
        listRank.add("吐槽排序");
        listRank.add("更新排序");
        listRank.add("打赏排序");
    }

    private void intData() {
        OkHttpUtils.post(HttpManager.IP + "/stacks-bookFiltering")
                .params("bookLabid", lableid)
                .params("bookWorldCount", String.valueOf(numPosition))
                .params("bookStatus", String.valueOf(zhuangTaiPosition))
                .params("updateTime", String.valueOf(timePosition))
                .params("order", String.valueOf(rankPosition + 1))
                .params("startPage", String.valueOf(page))
                .execute(new StringCallback() {
                    @Override
                    public void onBefore(BaseRequest request) {
                        super.onBefore(request);
                        if (noBackgLodDialog==null){
                            noBackgLodDialog=new LoadviewDialog(ClassfimuchActivity.this);
                        }
                        noBackgLodDialog.show();
                    }

                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        if (noBackgLodDialog!=null){
                            noBackgLodDialog.dismiss();
                        }
                        refreshClassify.finishLoadMore();
                        refreshClassify.finishRefresh();
                        Gson gson = new Gson();
                        try {
                            booklistBean = gson.fromJson(s, BiaoqianmoreBean.class);
                            if (booklistBean.getReturnCode() == 200) {
                                booklist.addAll(booklistBean.getData().getList());
                                adapter.notifyDataSetChanged();
                                if (booklist.size() < 1) {
                                    nodatasClassfy.setVisibility(View.VISIBLE);
                                } else {
                                    nodatasClassfy.setVisibility(View.GONE);
                                }

                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }


                    }
                });

    }

    @OnClick({R.id.back_classfymuch, R.id.seniority, R.id.screen})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back_classfymuch:
                goBack();
                break;
            case R.id.seniority:
                if (popuWindowRank != null && !popuWindowRank.isShowing()) {
                    popuWindowRank.showAsDropDown(view);
                } else {
                    showPopuWindow(view, 1);
                }
                rankimage.setImageResource(R.drawable.up);
                break;
            case R.id.screen:
                if (popupWindow != null && !popupWindow.isShowing()) {
                    popupWindow.showAsDropDown(view);

                } else {
                    showPopuWindow(view, 0);
                }
                shaixuanimage.setImageResource(R.drawable.up);
                break;
        }
    }


    private void showPopuWindow(View view, int i) {
        View contentView = null;
        switch (i) {
            case 0:
                contentView = LayoutInflater.from(this).inflate(R.layout.much_classfypopuwindoe, null);
                viewHolder = new RankViewHolder(contentView);
                numAdapter = new TextViewAdapter(R.layout.textitem, listNum, 0, this);
                viewHolder.bookNumRecycle.setAdapter(numAdapter);
                viewHolder.bookNumRecycle.setLayoutManager(new GridLayoutManager(this, 4));
                zhuangtaiAdapter = new TextViewAdapter(R.layout.textitem, listZhuangtai, 1, this);
                viewHolder.workestatusrecycle.setAdapter(zhuangtaiAdapter);
                viewHolder.workestatusrecycle.setLayoutManager(new GridLayoutManager(this, 4));
                timeAdapter = new TextViewAdapter(R.layout.textitem, listTime, 2, this);
                viewHolder.updatatimerecycle.setAdapter(timeAdapter);
                viewHolder.updatatimerecycle.setLayoutManager(new GridLayoutManager(this, 4));
                numAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        numPosition = position;
                        numAdapter.notifyDataSetChanged();
                    }
                });
                zhuangtaiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        zhuangTaiPosition = position;
                        zhuangtaiAdapter.notifyDataSetChanged();
                    }
                });
                timeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        timePosition = position;
                        timeAdapter.notifyDataSetChanged();
                    }
                });
                viewHolder.oknuchalssfy.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        page = 1;
                        booklist.clear();
                        intData();
                        popupWindow.dismiss();
                    }
                });
                popupWindow = new PopupWindow(contentView);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        shaixuanimage.setImageResource(R.drawable.downcoment);
                    }
                });
                //使其聚集
                popupWindow.setFocusable(true);
                // 设置允许在外点击消失
                popupWindow.setOutsideTouchable(true);
                //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
               // popupWindow.setBackgroundDrawable(new BitmapDrawable(getResources().getDrawable()));
                // 设置SelectPicPopupWindow弹出窗体的宽
                popupWindow.setWidth(ScreenUtils.getScreenWidth());
                popupWindow.setHeight(ScreenUtils.getScreenHeight()/ 2);
                // 设置SelectPicPopupWindow弹出窗体动画效果
                // popupWindow.setAnimationStyle(R.style.AnimBottom);
                popupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                popupWindow.showAsDropDown(view);
                break;
            case 1:
                contentView = LayoutInflater.from(this).inflate(R.layout.nuchclaff_rankpopu, null);
                ranrecycle = (RecyclerView) contentView.findViewById(R.id.muchclassfy_rankrecycle);
                rankAdapter = new TextViewAdapter(R.layout.textitem, listRank, 3, this);
                okrank = (SuperButton) contentView.findViewById(R.id.okmuclassrank);
                okrank.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        page = 1;
                        booklist.clear();
                        intData();
                        popuWindowRank.dismiss();
                    }
                });
                ranrecycle.setAdapter(rankAdapter);
                ranrecycle.setLayoutManager(new GridLayoutManager(this, 4));
                rankAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                        rankPosition = position;
                        rankAdapter.notifyDataSetChanged();
                    }
                });

                popuWindowRank = new PopupWindow(contentView);
                popuWindowRank.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        rankimage.setImageResource(R.drawable.downcoment);
                    }
                });
                //使其聚集
                popuWindowRank.setFocusable(true);
                // 设置允许在外点击消失
                popuWindowRank.setOutsideTouchable(true);
                //这个是为了点击“返回Back”也能使其消失，并且并不会影响背景
                popuWindowRank.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                // 设置SelectPicPopupWindow弹出窗体的宽
                popuWindowRank.setWidth(ScreenUtils.getScreenWidth());
                popuWindowRank.setHeight(ScreenUtils.getScreenHeight()  / 5);
                // 设置SelectPicPopupWindow弹出窗体动画效果
                // popupWindow.setAnimationStyle(R.style.AnimBottom);
                //popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_search_img));
                popuWindowRank.showAsDropDown(view);
                break;

        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (classfymuchtop!=null){
            classfymuchtop.getBackground().setAlpha(255);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        popupWindow = null;
        popuWindowRank = null;
        System.gc();
        System.runFinalization();
        System.gc();
    }

    static class RankViewHolder {
        @BindView(R.id.bookNum_recycle)
        RecyclerView bookNumRecycle;
        @BindView(R.id.workestatusrecycle)
        RecyclerView workestatusrecycle;
        @BindView(R.id.updatatimerecycle)
        RecyclerView updatatimerecycle;
        @BindView(R.id.okmuchclass)
        SuperButton oknuchalssfy;


        RankViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
